package com.coai.user.repository

import com.coai.user.model.*
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository

@Repository
interface OrganizationRepository : JpaRepository<Organization, String> {
    
    fun findByParentIdOrderBySortOrder(parentId: String?): List<Organization>
    
    fun findByCode(code: String): Organization?
    
    fun existsByCode(code: String): Boolean
}

@Repository
interface UserOrganizationRepository : JpaRepository<UserOrganization, String> {
    
    fun findByUserId(userId: String): List<UserOrganization>
    
    fun findByOrganizationId(organizationId: String): List<UserOrganization>
    
    fun findByUserIdAndIsPrimary(userId: String, isPrimary: Boolean): UserOrganization?
    
    fun existsByUserIdAndOrganizationId(userId: String, organizationId: String): Boolean
}

@Repository
interface RoleRepository : JpaRepository<Role, String> {
    
    fun findByCode(code: String): Role?
    
    fun findByEnabledTrue(): List<Role>
    
    fun existsByCode(code: String): Boolean
}

@Repository
interface UserRoleRepository : JpaRepository<UserRole, String> {
    
    fun findByUserId(userId: String): List<UserRole>
    
    fun findByRoleId(roleId: String): List<UserRole>
    
    fun existsByUserIdAndRoleId(userId: String, roleId: String): Boolean
    
    fun deleteByUserIdAndRoleId(userId: String, roleId: String)
    
    @Query("SELECT ur.roleId FROM UserRole ur WHERE ur.userId = :userId")
    fun findRoleIdsByUserId(userId: String): List<String>
}

@Repository
interface PermissionRepository : JpaRepository<Permission, String> {
    
    fun findByCode(code: String): Permission?
    
    fun findByResource(resource: String): List<Permission>
    
    fun existsByCode(code: String): Boolean
}

@Repository
interface RolePermissionRepository : JpaRepository<RolePermission, String> {
    
    fun findByRoleId(roleId: String): List<RolePermission>
    
    fun findByPermissionId(permissionId: String): List<RolePermission>
    
    fun existsByRoleIdAndPermissionId(roleId: String, permissionId: String): Boolean
    
    fun deleteByRoleIdAndPermissionId(roleId: String, permissionId: String)
    
    @Query("SELECT rp.permissionId FROM RolePermission rp WHERE rp.roleId IN :roleIds")
    fun findPermissionIdsByRoleIds(roleIds: List<String>): List<String>
}
